<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class ZPituitaryUserContactRecords extends Model
{

    protected $table = 'z_pituitary_user_contact_records';

    protected $guarded = ['id'];

    /**
     *  保存联系记录
     * @param $params
     * @return int
     */
    public static function saveRecord($params) {

        $fields = Schema::getColumnListing("z_pituitary_user_contact_records");
        $data = array_intersect_key($params, array_flip($fields));
        return self::query()->insertGetId($data);
    }

    /**
     * 获取联系记录信息
     * @param $hospId
     * @param $deptId
     * @param $userId
     * @param $visitPeriod
     * @return array
     */
    public static function getPatientStatus($hospId, $deptId, $userId, $visitPeriod)
    {
        $sql = "select * from z_pituitary_user_contact_records 
                where user_id = ? 
                and visit_level = ? 
                and hosp_id = ? 
                and dept_id = ? 
                and status = 1 
                order by id desc limit 1";

        $ret = DB::selectOne($sql, [$userId, $visitPeriod, $hospId, $deptId]);

        $countDown = "0001-01-01 00:00:00";
        if (isset($ret->remind_date) && $ret->remind_date >= date("Y-m-d H:i:s")) {
            $countDown = $ret->remind_date;
        }

        $nextFollowup = "0001-01-01";
        if (isset($ret->next_followup) && $ret->next_followup >= date('Y-m-d')) {
            $nextFollowup = $ret->next_followup;
        }

        $sql2 = "select count(*) as cnt  from z_pituitary_user_contact_records 
                    where  user_id = ? 
                    and visit_level = ?
                    and hosp_id = ?
                    and dept_id = ?
                    and from_flg = 1";

        $ret2 = DB::selectOne($sql2, [$userId, $visitPeriod, $hospId, $deptId]);

        $ret3 = [
            "count_down"    => $countDown,
            "next_followup" => $nextFollowup,
            "status"    => isset($ret->status) ? $ret->status : 0,
            "sms_times" => isset($ret2->cnt) ? $ret2->cnt : 0
        ];
        return $ret3;
    }


    public static function getRecordList($userId, $hospId,$deptId,$page_no = 0,$page_size =10) {

        $offset = $page_no * $page_size;

        $sql = " select pr.*,hm.name from z_pituitary_user_contact_records pr 
 left join z_hosp_member hm on pr.doc_id = hm.id 
 where pr.user_id = '$userId'   and pr.hosp_id = '$hospId' and  pr.dept_id = '$deptId'  
 order by pr.id desc limit $offset ,$page_size";
        return DB::select($sql);
    }

    public static function getRecordListTotal($userId, $hospId,$deptId) {


        $sql = " select count(*) as cnt from z_pituitary_user_contact_records   
 where  user_id = '$userId'   and hosp_id = '$hospId' and  dept_id = '$deptId' ";
        $ret =  DB::selectOne($sql);
        return  $ret->cnt ?? 0 ;
    }



}
